package com.common.handler;

import cn.hutool.json.JSONUtil;
import com.common.enums.ApiResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Description: 系统默认身份验证失败的处理器
 * @Date: 2025/6/6 15:01
 */
public class SystemDefaultAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        String message = exception.getMessage();
        ApiResult responseResult = ApiResult.failure(message);
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        printWriter.print(JSONUtil.parseObj(responseResult).toStringPretty());
        printWriter.flush();
        printWriter.close();
    }
}
